package com.feng.freader.view.pintu;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


//import androidx.annotation.RequiresApi;
//
//import com.example.puzzlegame.Page.PuzzlePage;
//import com.example.puzzlegame.Page.TakePicturesPage;
//import com.example.puzzlegame.Utils.FileUtils;
//import com.example.puzzlegame.Utils.ImagesUtil;
//import com.example.puzzlegame.Utils.MiHelper;
//import com.example.puzzlegame.Utils.PhotoUtil;
//import com.example.puzzlegame.Utils.SizeHelper;
//import com.example.puzzlegame.Utils.Typefaces;

import com.feng.freader.R;
import com.feng.freader.view.pintu.Page.PuzzlePage;
import com.feng.freader.view.pintu.Page.TakePicturesPage;
import com.feng.freader.view.pintu.Utils.SizeHelper;
import com.feng.freader.view.pintu.Utils.Typefaces;

import java.io.BufferedInputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class WelcomePage extends Activity {
    //welecomePage启动界面
    private LinearLayout group ;
    private Button button1, button2, button3,button4 ;
    //private boolean modelFlag = false;  //用来区分休闲模式

    //@SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //StatusBarUtil.transparencyBar(this);//修改状态栏为全透明
        setContentView(R.layout.activity_01);//加载xml布局资源

        //askPermissions();
        initView();//初始化按钮和布局
        setTextTypeface();//initialize the text display(字型)

        HandlerThread handlerThread = new HandlerThread("HandlerThread");
        handlerThread.start();//开启子线程
/*        Thread handlerThread = new Thread(start);
        thread.start();//开启子线程*/

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                finally {
                    Message message = new Message();
                    message.what = 1;
                    mHandler.sendMessage(message);
                }
                // 通过sendMessage（）发送

            }
        }.start();
    }


/*
    //调用Runnable接口开启子线程（当然继承 Thread也可以
    Runnable start = () -> {
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Message message = new Message();
            message.what = 1;
            mHandler.sendMessage(message);
        }
    };
*/

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    AlphaAnimation animation = new AlphaAnimation(0, 1);//布局持续动画的渐变效果，开始透明度为0，最终透明度为1
                    animation.setAnimationListener(new Animation.AnimationListener() {//监听动画运行过程
                        @Override
                        public void onAnimationStart(Animation animation) {}

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            setButtonEnabled(true);
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {}
                        //这三个方法分别是Animation开始的时候调用，完成的时候调用，重复的时候调用
                    });
                    animation.setDuration(1000);//动画持续效果为1s
                    group.startAnimation(animation);//启动动画
                    group.setAlpha(1);
                    break;
                case 2:

                    Intent intent2 = new Intent(WelcomePage.this, TakePicturesPage.class);
                    //intent2.putExtra("modelFlag", modelFlag);
                    startActivity(intent2);
                    break;
            }
        }
    };


    //设置字体样式
    private void setTextTypeface() {
        TextView splashTitle = (TextView) findViewById(R.id.splash_title);
        TextView t2 = (TextView) findViewById(R.id.t2);
        TextView version = (TextView) findViewById(R.id.version);

        SizeHelper.prepare(this);
        splashTitle.setTextSize(SizeHelper.fromPx(30));
        Log.d("TAG","size " + splashTitle.getTextSize());
        t2.setTextSize(SizeHelper.fromPx(12));
        t2.setTypeface(Typefaces.get(this, "Satisfy-Regular.ttf"));
        version.setTypeface(Typefaces.get(this, "Satisfy-Regular.ttf"));
    }


//初始并实例化控件
    private void initView() {
        group = (LinearLayout) findViewById(R.id.button_group) ;
        group.setAlpha(0);//设置布局透明度
        //实例化
        button1 = (Button) findViewById(R.id.button1) ;
        button2 = (Button) findViewById(R.id.button2) ;
        button3 = (Button) findViewById(R.id.button3) ;
        button4 = findViewById(R.id.button4);

      //  button1.setEnabled(false);
        //button2.setEnabled(false);
        //button3.setEnabled(false);
        setButtonEnabled(false);
    }


    private void setButtonEnabled(boolean enable){
        button1.setEnabled(enable);
        button2.setEnabled(enable);
        button3.setEnabled(enable);

    }




//按钮触发函数
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void onClick(View v){
        switch (v.getId()){
            case R.id.button1:
                // 弹出对话框，需要用Builder方法创建
                final AlertDialog.Builder builder = new AlertDialog.Builder(WelcomePage.this);
                builder.setTitle("难度选择：");
                builder.setSingleChoiceItems(new String[]{"初级", "中级", "高级"}, 0,
                        (dialog, which) -> {    //原本是 new DialogInterface.OnClickListener()，
                                                //jdk1.8会 建议如下： Anonymous new DialogInterface.OnClickListener() can be replaced with lambda，用lambda代替

                            switch (which){
                                case 0:
                                    PuzzlePage.GAME_TYPE = 3;
                                    break;
                                case 1:
                                    PuzzlePage.GAME_TYPE = 4;
                                    break;
                                case 2:
                                    PuzzlePage.GAME_TYPE = 5;
                                    break;
                            }
                        });

                builder.setPositiveButton("确定", (dialog, which) -> new AlertDialog.Builder(WelcomePage.this).setTitle("选择图片").setItems(
                        new String[] { "从图库中选择", "自带图片" }, (dialog1, which1) -> {
                            switch(which1){
                                /**
                                 * 从图库获取图片，通配符*遍历图片
                                 */
                                case 0:

                                     selectPic();//用于跳转系统相册的函数

/*
                                    Intent intent = new Intent(Intent.ACTION_PICK);
                                    //这个地方用ACTION_GET_CONTENT可能会出现绝对路径问题？？
                                    intent.setType("image/*");
                                    // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY(根据需求自己设置的，直接写value值也行)
                                    startActivityForResult(intent, PHOTO_REQUEST);//回调函数，返回值
*/

                                    //Intent intent = new Intent(Intent.ACTION_PICK);
                                    //这个地方用ACTION_GET_CONTENT可能会出现绝对路径问题？？
                                    //ACTION_GET_CONTENT：允许用户选择特殊种类的数据，并返回（特殊种类的数据：照一张相片或录一段音频
                                  /*  intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                            "image/*");*/
                                  //  startActivityForResult(intent, 1);	//回调函数，返回值
                                    break;
                                /**
                                 * 自带图片，handler机制
                                 */
                                case 1:
                                    mHandler.sendEmptyMessage(2);
                                    break;
                            }
                        }).show());

                builder.setNegativeButton("取消", (dialog, which) -> {

                });
                builder.show();
                break;
                //游戏帮助
            case R.id.button2:
                AlertDialog.Builder builder1 = new AlertDialog.Builder(WelcomePage.this);
                builder1.setMessage("点击开始游戏可以选择难度，可以选择本地图片或者游戏自带图片，进入已打乱" +"\n"+
                                    "的游戏页面，选择一片要移动的图片，即可再拖向相邻的空白区域最下方有静音" +"\n"+
                                    "按钮，长按叹号即可显示完整图片，也可以按第三个按钮重新选择难度，点击"+"\n"+
                                    "第四个按钮可以重置初始位置"
                );
                builder1.setTitle("游戏帮助");

                builder1.create().show();
                break;
                //退出
            case R.id.button3:
                new AlertDialog.Builder(this).setMessage("确定要退出游戏吗？").setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id) {

                        Intent MyIntent = new Intent(Intent.ACTION_MAIN);
                        MyIntent.addCategory(Intent.CATEGORY_HOME);
                        startActivity(MyIntent);
                        finish();

                    }

                }).show();
                break;
                //休闲模式 采用自带简单图片，3x3切割
            case R.id.button4:
                PuzzlePage.GAME_TYPE = 3;
                PuzzlePage.flag = false;
                //modelFlag = true;
                mHandler.sendEmptyMessage(2);
                break;

        }
    }

/*

    public void getGalleryIntent()
    {
        */
/**19之后的系统相册的图片都存在于MediaStore数据库中；19之前的系统相册中可能包含不存在与数据库中的图片，所以如果是19之上的系统
         * 跳转到19之前的系统相册选择了一张不存在与数据库中的图片，解析uri时就可能会出现null*//*

        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT < 19) {
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
        }
        startActivityForResult(intent, PHOTO_REQUEST);//回调函数，返回值
    }
*/
    /**
     * 打开本地相册选择图片
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @SuppressLint("IntentReset")
    private void selectPic(){

        Intent intent;
         if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, 0);
      /*  Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                "image/*");
        startActivityForResult(intent, 0);	//回调函数，返回值
*/


    }



    //因为读取相册权限缘故添加的函数
    private void askPermissions() {//动态申请权限！
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS,//联系人的权限
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};//读写SD卡权限
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }
        }
    }



    // @SuppressLint("MissingSuperCall")// @SuppressLint标注忽略指定的警告
    @Override
    //调用startActivityForResult（）方法来跳转页面的时候需要重写onActivityResult方法
    public void onActivityResult(int requestCode, int resultCode, Intent data) {


        if (resultCode == RESULT_OK) {
            if (requestCode == 0 && data != null) {

                Log.d("data", "data+" + data.getData());
                Cursor cursor = this.getContentResolver().query(
                        data.getData(), null, null, null, null);
                cursor.moveToFirst();
                String imagePath = cursor.getString(
                        cursor.getColumnIndex("_data"));
                Log.d("data", "data-" + imagePath);
                Intent intent = new Intent(WelcomePage.this, PuzzlePage.class);//跳转
                intent.putExtra("imagePath", imagePath);
                cursor.close();
                startActivity(intent);
            }
        }
    }


/*        if (resultCode == RESULT_OK){
            if (requestCode == 1 && data != null){

                Log.d("data","data+"+data.getData());
                Cursor cursor = this.getContentResolver().query(
                        data.getData(), null, null, null, null);
                cursor.moveToFirst();
                String imagePath = cursor.getString(
                        cursor.getColumnIndex("_data"));
                Log.d("data","data-"+imagePath);
                Intent intent = new Intent(WelcomePage.this, PuzzlePage.class);
                intent.putExtra("imagePath", imagePath);
                cursor.close();
                startActivity(intent);*/

       /* super.onActivityResult(requestCode, resultCode, data);
        //应该是四大组件的内容提供者对应的内功接收者 ，必调方法
        ContentResolver contentResolver = getContentResolver();
        Bitmap bitmap = null;

            if (requestCode == 0) {
                //图片的Uri
                Uri uri = data.getData();
                Log.e("tag", "uri = " + uri);


                String[] filePathColumn = {MediaStore.MediaColumns.DATA};

                assert uri != null;
                Cursor cursor = contentResolver.query(uri, filePathColumn, null, null, null);
//            也可用下面的方法拿到cursor
//            Cursor  cursor  =  this.context.managedQuery(uri,  filePathColumn,  null,  null,  null);
                assert cursor != null;
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String imagePath1 = cursor.getString(columnIndex);//cursor.getString()取出当前图片的路径返回path

                Intent intent1 = new Intent(WelcomePage.this, PuzzlePage.class);
                intent1.putExtra("imagePath1", imagePath1);
                cursor.close();

                startActivity(intent1);*/      /*页面跳转*/


                /*putExtra("A",B)中，AB为键值对，第一个参数为键名，第二个参数为键对应的值。
                顺便提一下，如果想取出Intent对象中的这些值，需要在另一个Activity中用getXXXXXExtra方法，
                注意需要使用对应类型的方法，参数为键名,
                */





/*            Log.d("data","data+"+data.getData());
                Cursor cursor = this.getContentResolver().query(    //ContentResolver为内容解析器,理解为解读相册内容
                        //( uri ,projection ,查询where字句 ,查询条件属性值 ,结果排序规则 )
                        data.getData(), null, null, null, null);

                if (cursor == null) {
                    Toast.makeText(this, "图片没找到", Toast.LENGTH_SHORT).show();
                    return;
                }

                cursor.moveToFirst();//将cursor移动到第一条记录上
                //获得图片路径
                String imagePath = cursor.getString(
                        cursor.getColumnIndex("_data"));//获得用户所选照片的索引值，然后根据索引值获取路径
                Log.d("data","data-"+imagePath);
                Intent intent = new Intent(WelcomePage.this, PuzzlePage.class);//从WelcomePage跳转到PuzzlePage
                intent.putExtra("imagePath", imagePath);
                *//*putExtra("A",B)中，AB为键值对，第一个参数为键名，第二个参数为键对应的值。
                  顺便提一下，如果想取出Intent对象中的这些值，需要在另一个Activity中用getXXXXXExtra方法，
                  注意需要使用对应类型的方法，参数为键名,
                *//*
                cursor.close();

                startActivity(intent);//页面跳转
            }

    }
*/



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
//弹出确定退出对话框
        if(keyCode == KeyEvent.KEYCODE_BACK) {

            //setPositiveButton表示设置弹框后的确定按钮
            new AlertDialog.Builder(this).setMessage("确定要退出游戏吗？").setPositiveButton("确定", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {

                    Intent MyIntent = new Intent(Intent.ACTION_MAIN);
                    MyIntent.addCategory(Intent.CATEGORY_HOME);//使Intent指向Home界面
                    startActivity(MyIntent);
                    finish();

                }

            }).show();

        }
        return true;
    }



}
